package com.bldby.baselibrary.core.ui.baseactivity;

import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Build;
import android.os.Bundle;

import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.LinearLayout;


import com.alibaba.android.arouter.launcher.ARouter;
import com.bldby.baselibrary.R;
import com.bldby.baselibrary.app.GlobalUtil;
import com.bldby.baselibrary.core.rxbus.RxBus;
import com.bldby.baselibrary.core.ui.basefragment.BaseBfragment;
import com.bldby.baselibrary.core.util.DeviceUtil;
import com.bldby.baselibrary.core.util.ToastUtil;
import com.bldby.baselibrary.core.util.doubleclick.XClickUtil;
import com.bldby.baselibrary.databinding.LayoutLoadingViewBinding;
import com.gyf.immersionbar.ImmersionBar;

import java.util.ArrayList;

import io.reactivex.disposables.Disposable;
import me.yokeyword.fragmentation.SupportActivity;
import pl.droidsonroids.gif.GifDrawable;

public abstract class BaseBActivity extends SupportActivity implements NavigationCallback {
//初始化
    //获取数据三种方式
    //1.通过Autowired注解表明key   &  需要在onCreate中调用ARouter.getInstance().inject(this);配合使用
//    @Autowired(name = "key1")
//    public long data;
    //2.通过Autowired注解 & 将key1作为属性的名称   &  需要在onCreate中调用ARouter.getInstance().inject(this);配合使用
//    @Autowired()
//    public long key1;
    //3.通过Bundle获取
//    getIntent().getExtras().getLong("key1")

    // 获取Fragment
//    Fragment fragment = (Fragment) ARouter.getInstance().build("/test/fragment").navigation();
//    @Route(path = RouteConstants.APPMAIN, extras = RouteLoginConstants.SHOWCHECKLOGIN)
    //当extras = RouteLoginConstants.SHOWCHECKLOGIN时
    AlertDialog loadingPopup;

    public boolean lazyInit = true;
    private GifDrawable animationDrawable;
    public BaseBActivity activity;
    public NavigationCallback navigationCallback = this;
    public ArrayList<Disposable> disposables = new ArrayList<>();


    public void addDisposable(Disposable disposable) {
        disposables.add(disposable);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.e("TAG", "onCreate: " + this.getClass().getName());
        activity = this;
        if (android.os.Build.VERSION.SDK_INT == Build.VERSION_CODES.O) {
            //Android8.0 你自己的逻辑代码，样式不透明

        } else {
            //其他版本的代码
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

        }
        ARouter.getInstance().inject(this);
        if (getOpenImmersionBar() != null) {
            getOpenImmersionBar();
        }
        bindIngView();
        GlobalUtil.setCurrentActivity(this);
        if (lazyInit) {
            initView();
            initListener();
            loadData();
            lazyInit = false;
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        Log.e("TAG", "onStart: " + this.getClass().getName());
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        Log.e("TAG", " onRestart" + this.getClass().getName());

    }

    @Override
    protected void onResume() {
        super.onResume();
        GlobalUtil.setCurrentActivity(this);
        Log.e("TAG", " onResume" + this.getClass().getName());
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.e("TAG", " onPause" + this.getClass().getName());
    }

    @Override
    protected void onStop() {
        super.onStop();
        Log.e("TAG", " onStop " + this.getClass().getName());

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        GlobalUtil.setCurrentActivity(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        for (Disposable disposable : disposables) {
            if (disposable.isDisposed()) {
                disposable.dispose();
            }
        }
        goneloadDialog();
//        loadingPopup = null;
        activity = null;
    }

    @Override
    public View onCreateView(View parent, String name, Context context, AttributeSet attrs) {
        if (getOpenImmersionBar() != null) {
            getOpenImmersionBar().init();
        }
        return super.onCreateView(parent, name, context, attrs);
    }

    public abstract void bindIngView();

    public abstract void initView();

    public abstract void loadData();

    public abstract void initListener();

    //解决EditText和软键盘的问题
    // 第一种方案.keyboardEnable(true)
    //第二种方案 不使用keyboardEnable方法，只需要在布局的根节点（最外层节点）加上android:fitsSystemWindows="true"属性即可，只适合纯色状态栏
    public ImmersionBar getOpenImmersionBar() {
        return ImmersionBar.with(this)
                .fitsSystemWindows(true)
                .statusBarDarkFont(true, 0.2f)
                .navigationBarColor(R.color.white)
                .statusBarColor(R.color.white)
                .navigationBarDarkIcon(true);
    }

    public void onClickBack(View v) {
        goneloadDialog();
        finish();
    }

    protected void showloadDialog() {

        if (loadingPopup == null) {
            LayoutLoadingViewBinding inflate = LayoutLoadingViewBinding.inflate(getLayoutInflater());
            loadingPopup = new AlertDialog.Builder(this, R.style.TransparentDialog)
                    .setView(inflate.getRoot())
                    .setCancelable(false)
                    .create();
            loadingPopup.getWindow().setDimAmount(0f);

            loadingPopup.show();
            int i = DeviceUtil.dp2px(this, GlobalUtil.getCurrentActivity().getResources().getDimension(R.dimen.dp_50));
            loadingPopup.getWindow().setLayout(i, LinearLayout.LayoutParams.WRAP_CONTENT);
            animationDrawable = (GifDrawable) inflate.img.getDrawable();
            animationDrawable.start();
            loadingPopup.show();
        }


    }

    protected void goneloadDialog() {
        try {
            if (null != loadingPopup) {
                loadingPopup.dismiss();
                loadingPopup = null;
                animationDrawable.stop();
                animationDrawable = null;
            }
        }catch (Exception exception){
            exception.printStackTrace();
        }
    }
//
//    @Override
//    public Resources getResources() {
//        Resources res = super.getResources();
//        Configuration configuration = res.getConfiguration();
//        if (configuration.fontScale != 1.0f) {
//            configuration.fontScale = 1.0f;
//            res.updateConfiguration(configuration, res.getDisplayMetrics());
//        }
//        return res;
//    }

    public void start(String url) {
        // 使用两个参数的navigation方法，可以获取单次跳转的结果
        //basefirst
        //basetwo
        //basethree
        ARouter.getInstance()
                .build(url)
                .withTransition(R.anim.anim_in, R.anim.anim_out)
                .navigation(this, this);

    }

    /*
     * 需要上个页面回调返回参数的
     * */
    public void start(String url, int requestCode) {
        ARouter.getInstance()
                .build(url)
                .withTransition(R.anim.anim_in, R.anim.anim_out)
                .navigation(this, requestCode, this);
    }

    /**
     * 设置传递参数
     *
     * @param url
     * @param bundle
     */
    public void start(String url, Bundle bundle) {
        Postcard build = ARouter.getInstance().build(url);
        build.with(bundle);
        build.navigation(this, this);
    }

    /**
     * 自定义参数 需要手动调用 .navigation(this, this)
     * ARouter.getInstance().build("/test/1")
     * .withLong("key1", 666L)
     * .withString("key3", "888")
     * .withSerializable("key4", new Test("Jack", "Rose"))
     * .withObject("map", map)
     * .navigation();
     * 也可直接获取fragment
     * 最后可以跳转时一定要使用navigation(this, this)才可以获取回调
     *
     * @param url
     * @return
     */
    public Postcard startWith(String url) {
        Postcard build = ARouter.getInstance().build(url);
        return build;
    }

//    又返回参数的跳转
//    startActivityForResult();
//    navigation(Context mContext, int requestCode, NavigationCallback callback)

    public BaseBfragment getFragment(String url) {
        // 获取Fragment
        BaseBfragment fragment = (BaseBfragment) ARouter
                .getInstance()
                .build(url)
                .navigation(this, this);
        return fragment;
    }

    /**
     * 设置传递参数
     *
     * @param url
     * @param bundle
     */
    public BaseBfragment getFragmentWithBundle(String url, Bundle bundle) {
        BaseBfragment fragment = (BaseBfragment) ARouter
                .getInstance()
                .build(url)
                .with(bundle)
                .navigation(this, this);
        return fragment;
    }


    //跳转成功返回
    @Override
    public void onFound(Postcard postcard) {

    }

    //找不到的时候回调
    @Override
    public void onLost(Postcard postcard) {
        ToastUtil.show(getString(R.string.nofoundView));
    }

    //跳转结束
    @Override
    public void onArrival(Postcard postcard) {

    }

    //被拦截
    @Override
    public void onInterrupt(Postcard postcard) {
        ToastUtil.show("被拦截");
    }

    @Override
    public Resources getResources() {//还原字体大小
        Resources res = super.getResources();
        //非默认值
        if (res.getConfiguration().fontScale != 1) {
            Configuration newConfig = new Configuration();
            newConfig.setToDefaults();//设置默认
            res.updateConfiguration(newConfig, res.getDisplayMetrics());
        }
        return res;
    }

    public void showKeyboard(Context context, final View view) {
        // 必须给控件加这个方法，否则无效
        view.requestFocus();
        Log.e("TAG", "showKeyboard: ");
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.showSoftInput(view, InputMethodManager.RESULT_SHOWN);
        imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY);

    }

    /**
     * 隐藏软键盘
     *
     * @param context
     * @param view
     */
    public void hideSoftKeyboard(Context context, View view) {
        if (view == null)
            return;
        InputMethodManager inputMethodManager = (InputMethodManager) context.getSystemService(
                Context.INPUT_METHOD_SERVICE);
        if (inputMethodManager.isActive())
            inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
    }
}